﻿using BoilerplateWPF.Helpers;
using BoilerplateWPF.Models;
using BoilerplateWPF.Services.Interfaces;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BoilerplateWPF.Services
{
    public class UserService : IUserService
    {
        public UserModel ValidateUserLogin(string userAccount, string password, int identity)
        {
            // SELECT * FROM user_info WHERE user_account = "1" AND user_password = "1" AND identity_id = "1"
            string sql = @"SELECT * FROM user_info 
                                    WHERE user_account = @account 
                                    AND user_password = @password 
                                    AND identity_id = @identity";

            var parameters = new MySqlParameter[]
            {
                new MySqlParameter("@account", MySqlDbType.VarChar) { Value = userAccount },
                new MySqlParameter("@password", MySqlDbType.VarChar) { Value = password },
                new MySqlParameter("@identity", MySqlDbType.Int32) { Value = identity }
            };

            var results = MysqlHelper.ExecuteQuery(sql, MapUserModel, parameters);
            return results.FirstOrDefault(); // 返回第一个或null
        }

        private UserModel MapUserModel(IDataRecord record)
        {
            return new UserModel
            {
                UserAccount = record["user_account"].ToString(),
                UserName = record["user_name"].ToString(),
                UserPassword = record["user_password"].ToString(),
                IdentityID = Convert.ToInt32(record["identity_id"])
                // 不设置 RankName 因为它是计算属性 数据表中是没有的 只在数据模型中存在 所以不需要映射 而且只读 也无法映射
                //RankName = record["RankName"].ToString()
            };
        }
    }
}
